// api.youraitools.co (Cloudflare Pages Functions): domain index + transparent proxy to the x402 Workers.
import { route, forward, upstreamRequest } from './proxy.js';
import { indexJson, indexHtml, wellKnown, combinedOpenapi, llmsTxt } from './root.js';
import { BY_PREFIX, SERVICE_BY_PREFIX } from './tools.js';
import { whichApiHtml, whichApiMd, llmsFullTxt } from './docs.js';
import { swr, cacheKey, cacheableToolRequest, storable, TTL } from './cache.js';
const cors = { 'access-control-allow-origin': '*' };
const json = (o, { status = 200, headers = {} } = {}) => new Response(JSON.stringify(o, null, 2), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'public, max-age=300', ...cors, ...headers } });
const prefersHtml = (a = '') => /text\/html/.test(a) && !/^application\/json/.test(a);
// Aggregate discovery doc (fans out to every tool Worker): cached, SWR, partials never replace a good copy.
function aggregate(request, env, waitUntil, build) {
const url = new URL(request.url);
return swr({
key: cacheKey(`${url.origin}${url.pathname}`), waitUntil, head: request.method === 'HEAD',
produce: async () => { const meta = {}; const doc = await build(env, meta); const complete = meta.failed.length === 0; return { res: json(doc, { headers: complete ? {} : { 'x-yat-partial': meta.failed.join(',') } }), complete }; },
});
}
// Per-tool static discovery routes (landing, /.well-known/x402, /openapi.json, favicons, og images).
// Only plain GET/HEAD with no query and no payment/auth headers; only 200s without no-store/cookies are stored.
function toolCached(request, r, env, waitUntil) {
const url = new URL(request.url);
const acceptInKey = r.rest === '/';
return swr({
key: cacheKey(`${url.origin}${url.pathname === `/${r.tool.prefix}` ? `/${r.tool.prefix}/` : url.pathname}`, acceptInKey ? { accept: request.headers.get('accept') } : {}),
waitUntil, head: request.method === 'HEAD',
clientCC: () => null,
produce: async () => {
const res = await forward(new Request(request.url, { method: 'GET', headers: request.headers }), r.tool, r.rest, env);
if (!storable(res, { acceptInKey })) return { res, complete: false, storable: false };
const headers = new Headers(res.headers);
if (!headers.has('cache-control')) headers.set('cache-control', `public, max-age=${TTL}`);
return { res: new Response(res.body, { status: res.status, statusText: res.statusText, headers }), complete: true };
},
});
}
export async function onRequest(context) {
const { request, env } = context;
const waitUntil = typeof context.waitUntil === 'function' ? (p) => context.waitUntil(p) : undefined;
const url = new URL(request.url);
const r = route(url.pathname);
if (r) return cacheableToolRequest(request, r.rest) ? toolCached(request, r, env, waitUntil) : forward(request, r.tool, r.rest, env);
if (!['GET', 'HEAD'].includes(request.method)) {
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: { ...cors, 'access-control-allow-methods': 'GET, HEAD, OPTIONS', 'access-control-max-age': '86400' } });
return json({ error: 'not_found', message: 'Use /<tool>/... (see /)' }, { status: 404, headers: { 'cache-control': 'no-store' } });
}
switch (url.pathname) {
case '/':
if (prefersHtml(request.headers.get('accept') || '')) return new Response(indexHtml(env), { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=300', vary: 'Accept' } });
return new Response(JSON.stringify(indexJson(env), null, 2), { headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'public, max-age=300', vary: 'Accept', ...cors } });
case '/index.json': return json(indexJson(env));
case '/.well-known/x402': return aggregate(request, env, waitUntil, wellKnown);
case '/openapi.json': return aggregate(request, env, waitUntil, combinedOpenapi);
case '/health': return json({ ok: true, tools: Object.keys(BY_PREFIX), services: Object.keys(SERVICE_BY_PREFIX) }, { headers: { 'cache-control': 'no-store' } });
case '/robots.txt': return new Response('User-agent: *\nAllow: /\n\nSitemap: https://api.youraitools.co/sitemap.xml\n', { headers: { 'content-type': 'text/plain' } });
case '/llms.txt': return new Response(llmsTxt(env), { headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'public, max-age=300' } });
case '/llms-full.txt': return new Response(llmsFullTxt(env), { headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'public, max-age=300', ...cors } });
case '/docs': case '/docs/': case '/which-api': return new Response(null, { status: 301, headers: { location: '/docs/which-api', 'cache-control': 'public, max-age=3600' } });
case '/docs/which-api': return new Response(whichApiHtml(env), { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=300' } });
case '/docs/which-api.md': return new Response(whichApiMd(env), { headers: { 'content-type': 'text/markdown; charset=utf-8', 'cache-control': 'public, max-age=300', ...cors } });
case '/favicon.ico': case '/favicon.svg': return forward(request, BY_PREFIX.agentgate, url.pathname, env);
default: return json({ error: 'not_found', message: 'Unknown path. Tools live under /agentgate/, /webread/, /injectscan/, /domaincheck/, /payguard/, /pkgguard/, /stackdetect/, /tokenverdict/, /signcheck/, /counterpartycheck/, /x402fix/, /solverdict/, /agentready/, /perpradar/, /tasignal/, /leakguard/, /smartperps/, /toolpick/, /perpcheck/, /x402-template/, /credits/; services: /listing/ (see /).' }, { status: 404, headers: { 'cache-control': 'no-store' } });
}
}
export { upstreamRequest };
agentgate-source: code mirror on Cloudflare Pages. All repos